package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.PinyinUtil;
import com.joint.base.entity.*;
import com.joint.base.service.*;
import com.joint.web.action.BaseAdminAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by gcw on 2014/10/30.
 */
@ParentPackage("com")
public class AjaxRoleAction extends BaseAdminAction {
    @Resource
    private RoleService roleService;
    @Resource
    private UsersService usersService;
    @Resource
    private PermissionService permissionService;
    @Resource
    private FileManageService fileManageService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private PowerService powerService;

    private List<Permission> permissionList;
    private List<Users> usersList;
    private List<Role> roleList;
    private List<Power> powerList;

    private Users users;
    private Department department;
    private Power power;
    private Permission permission;
    private Role role;

    private String no;
    private String name;
    private String description;
    private String usersId;
    private String departId;
    private String powerId;
    private String permissionId;
    private String pName;

    protected Set<Users> usersSet;
    protected Set<Department> departmentsSet;
    protected Set<Power> powersSet;
    /**
     * 角色视图
     * @return
     */
    public String list(){
        Company company=usersService.getCompanyByUser();
        pager = new Pager();
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.asc);
        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        pager=roleService.findByPagerAndCompany(pager, null, company, params);
        roleList= (List<Role>) pager.getList();
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String,Object> data=new HashMap<String, Object>();
        Map<String,Object> map=null;
        for(Role role1:roleList){
            map=new HashMap<String, Object>();
            map.put("id",role1.getId());
            map.put("pName",role1.getPName());
            map.put("name",role1.getName());
            map.put("description",role1.getDescription());
            dataRows.add(JSONObject.fromObject(map));
        }

        /*
        //升序排列
        JSONObject obj;
        for (int i=dataRows.size();i>0;--i){
            for (int n=0;n<i-1;n++){
                 if (Integer.parseInt(dataRows.get(n).get("no").toString()) > Integer.parseInt(dataRows.get(n+1).get("no").toString())){
                    obj = dataRows.get(n);
                    dataRows.set(n,dataRows.get(n+1));
                    dataRows.set(n+1, obj);
                }
            }
        }
        */

        long total =pager.getTotalCount();
        if(total%rows==0){
            total = total/rows;
        }else{
            if(total<rows){
                total = 1;
            }else{
                total = total/rows + 1;
            }
        }
        data.put("dataRows", JSONArray.fromObject(dataRows));
        data.put("records", pager.getTotalCount());
        data.put("page",page);
        data.put("rows",rows);
        data.put("total",total);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    /**
     * 角色添加和编辑
     * @return
     */
    public String input(){
        Company company=usersService.getCompanyByUser();
        if(StringUtils.isNotEmpty(keyId)){
            role=roleService.get(keyId);
            if (role != null){
                usersSet = role.getUsersSet();
                departmentsSet = role.getDepartSet();
                powersSet = role.getPowertSet();
            }
        }
        pager = new Pager(0);
        pager=usersService.findByPagerAndCompany(pager, null, company, new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        usersList= (List<Users>) pager.getList();
        pager = new Pager(0);
        pager=permissionService.findByPagerAndCompany(pager, null, company, new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        permissionList= (List<Permission>) pager.getList();
        return "input";
    }

    /**
     * 保存
     * @return
     */
    public String save(){
        if(StringUtils.isNotEmpty(keyId)){
            role=roleService.get(keyId);
        }
        else{
            role=new Role();
        }
        role.setNo(no);
        role.setName(name);
        role.setPName(pName);
        role.setState(BaseEnum.StateEnum.Enable);
        role.setDescription(description);
        role.setPinYin(PinyinUtil.getPingYin(name));
        role.setPinYinHead(PinyinUtil.getPinYinHeadChar(name));
        role.setCompany(usersService.getCompanyByUser());
        if (StringUtils.isNotEmpty(usersId)){
            String arr[] = usersId.split(",");
            usersSet = new HashSet<Users>();
            for (int i=0; i<arr.length;i++){
                users = usersService.get(arr[i]);
                if (users != null){
                    usersSet.add(users);
                }
            }
            role.setUsersSet(usersSet);
        }

        if (StringUtils.isNotEmpty(departId)){
            String arr[] = departId.split(",");
            departmentsSet = new HashSet<Department>();
            for (int i=0; i<arr.length;i++){
                department = departmentService.get(arr[i]);
                if (department != null){
                    departmentsSet.add(department);
                }
            }
            role.setDepartSet(departmentsSet);
        }

        if (StringUtils.isNotEmpty(powerId)){
            String arr[] = powerId.split(",");
            powersSet = new HashSet<Power>();
            for (int i=0; i<arr.length;i++){
                power = powerService.get(arr[i]);
                if (power != null){
                    powersSet.add(power);
                }
            }
            role.setPowertSet(powersSet);
        }

        if(StringUtils.isNotEmpty(keyId)){
            roleService.update(role);
        }else{
            roleService.save(role);
        }
        return ajaxHtmlCallback("200", "提交成功！","操作状态");
    }

    /**
     * 显示树形
     * @return
     */
    public String zTree(){
        Company company=usersService.getCompanyByUser();
        Pager pager = new Pager(0);
        List<Permission> permissionList= (List<Permission>) permissionService.findByPagerAndCompany(pager, null, company, new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable}).getList();
        List<JSONObject> treeList = new ArrayList<JSONObject>();
        for(Permission per : permissionList){
            Map<String,Object> rMap = new HashMap<String, Object>();
            rMap.put("id",per.getId());
            rMap.put("pId",per.getParent()==null?"":per.getParent().getId());
            rMap.put("pName",per.getName());
            rMap.put("name",per.getLevel()+"|"+per.getName());
            rMap.put("intLevel",per.getLevel());
            rMap.put("open", false);
            rMap.put("roleId",keyId);
            rMap.put("halfCheck",false);
            if(StringUtils.isNotEmpty(keyId)){
                role = roleService.get(keyId);
                if(role!=null && role.getPermissionSet()!=null && role.getPermissionSet().contains(per)){
                    rMap.put("checked",true);
                }

            }

            treeList.add(JSONObject.fromObject(rMap));
        }
        Map<String, Object> data = new HashMap<String, Object>();
        data = new HashMap<String, Object>();
        data.put("data", JSONArray.fromObject(treeList));

        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
    }

    public String userGrid(){
        Company company=usersService.getCompanyByUser();
        pager = new Pager();
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setPageNumber(page);
        pager.setOrderBy("no");
        pager = usersService.findByPagerAndCompany(pager, null, company, new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        List<Users> usersList = (List<Users>) pager.getList();
        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(Users user : usersList){
            rMap = new HashMap<String, Object>();
            rMap.put("name",user.getName());
            rMap.put("email",user.getEmail());
            rMap.put("id",user.getId());
            String imgUrl = "";
            List<FileManage> fileManageList = fileManageService.getFileByKeyId(user.getId());
            if(fileManageList.size() > 0){
                FileManage fileManage = fileManageList.get(0);
                imgUrl = fileManage.getUrl();
            }
            rMap.put("userImg",imgUrl);
            rMap.put("roleId","");
            rMap.put("selected","");
            if(StringUtils.isNotEmpty(keyId)){
                rMap.put("roleId",keyId);
                role = roleService.get(keyId);
                if(role.getUsersSet().contains(user)){
                    rMap.put("selected","selected");
                }
            }
            dataRows.add(JSONObject.fromObject(rMap));
        }
        data.put("dataRows", JSONArray.fromObject(dataRows));
        data.put("records", pager.getTotalCount());
        data.put("page",page);
        data.put("rows",rows);
        data.put("total",Math.ceil((double)pager.getTotalCount()/pager.getPageSize()));
        return ajaxJson(JSONObject.fromObject(data).toString());
    }

    /**
     * 用户操作
     * @return
     */
    public String userConfig(){
        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlCallback("400", "请选择角色！","操作状态");
        }
        role = roleService.get(keyId);
        users = usersService.get(usersId);
        Set<Users> usersSet;
        if(role.getUsersSet()!=null){
            usersSet = role.getUsersSet();
        }else {
            usersSet = new HashSet<Users>();
        }
        if(usersSet.contains(users)){
            usersSet.remove(users);
        }else {
            usersSet.add(users);
        }
        role.setUsersSet(usersSet);
        roleService.update(role);
        return ajaxHtmlCallback("200", "操作成功！","操作状态");
    }

    public String permissionAddConfig(){
        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlCallback("400", "请选择角色！","操作状态");
        }
        role = roleService.get(keyId);
        permission = permissionService.get(permissionId);
        Set<Permission> permissionSet;
        if(role.getPermissionSet() !=null){
            permissionSet = role.getPermissionSet();
        }else {
            permissionSet = new HashSet<Permission>();
        }
        if(!permissionSet.contains(permission)){
            permissionSet.add(permission);
        }else {
            return null;
        }
        role.setPermissionSet(permissionSet);
        roleService.update(role);
        return ajaxHtmlCallback("200", permission.getName()+"加入成功！","操作状态");
    }
    public String permissionRemoveConfig(){
        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlCallback("400", "请选择角色！","操作状态");
        }
        role = roleService.get(keyId);
        permission = permissionService.get(permissionId);
        Set<Permission> permissionSet= role.getPermissionSet();
        if(permissionSet.contains(permission)){
            permissionSet.remove(permission);
        }else {
            return null;
        }
        role.setPermissionSet(permissionSet);
        roleService.update(role);
        return ajaxHtmlCallback("200", permission.getName()+"移除成功！","操作状态");
    }

    public String config(){
        pager = new Pager(0);
        roleList = (List<Role>) roleService.findByPager(pager,null,null).getList();
        return "config";
    }

    /**
     * 删除角色
     * @return
     */
    public String delete() {
        if (StringUtils.isEmpty(keyId)) {
            return ajaxHtmlCallback("200", "请选择角色！","操作状态");
        }
        role = roleService.get(keyId);
        role.setState(BaseEnum.StateEnum.Delete);
        roleService.update(role);
        return ajaxHtmlCallback("200", "删除成功！", "操作状态");
    }

    public List<Role> getRoleList() {
        return roleList;
    }

    public void setRoleList(List<Role> roleList) {
        this.roleList = roleList;
    }

    public Pager getPager() {
        return pager;
    }

    public void setPager(Pager pager) {
        this.pager = pager;
    }

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

    public String getNo() {
        return no;
    }

    public void setNo(String no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getUsersId() {
        return usersId;
    }

    public void setUsersId(String usersId) {
        this.usersId = usersId;
    }

    public String getPermissionId() {
        return permissionId;
    }

    public void setPermissionId(String permissionId) {
        this.permissionId = permissionId;
    }

    public Permission getPermission() {
        return permission;
    }

    public void setPermission(Permission permission) {
        this.permission = permission;
    }

    public Users getUsers() {
        return users;
    }

    public void setUsers(Users users) {
        this.users = users;
    }

    public List<Permission> getPermissionList() {
        return permissionList;
    }

    public void setPermissionList(List<Permission> permissionList) {
        this.permissionList = permissionList;
    }

    public List<Users> getUsersList() {
        return usersList;
    }

    public void setUsersList(List<Users> usersList) {
        this.usersList = usersList;
    }

    public String getPName() {
        return pName;
    }

    public void setPName(String pName) {
        this.pName = pName;
    }

    public String getPowerId() {
        return powerId;
    }

    public void setPowerId(String powerId) {
        this.powerId = powerId;
    }

    public String getDepartId() {
        return departId;
    }

    public void setDepartId(String departId) {
        this.departId = departId;
    }

    public Power getPower() {
        return power;
    }

    public void setPower(Power power) {
        this.power = power;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public Set<Users> getUsersSet() {
        return usersSet;
    }

    public void setUsersSet(Set<Users> usersSet) {
        this.usersSet = usersSet;
    }

    public Set<Department> getDepartmentsSet() {
        return departmentsSet;
    }

    public void setDepartmentsSet(Set<Department> departmentsSet) {
        this.departmentsSet = departmentsSet;
    }

    public Set<Power> getPowersSet() {
        return powersSet;
    }

    public void setPowersSet(Set<Power> powersSet) {
        this.powersSet = powersSet;
    }
}
